import api from '../../../api/index';
import dayjs from '../../../plugin/dayjs/index';
import daysbefore from '../../../plugin/daysbefore';
import * as echarts from '../../../components/ec-canvas/echarts';
const lsPlugin = requirePlugin("lzbluetooth");


//全局声明chart
var seriesDataArr = [];
var timeArr = [];
var chart = null;

// 时间格式化
function formatTime(date = new Date()) {
	return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
}
function formatDatelx (timestamp) {
	const date = new Date(timestamp * 1000);
	const year = date.getFullYear();
	const month = (date.getMonth() + 1).toString().padStart(2, '0');
	const day = date.getDate().toString().padStart(2, '0');
	const hours = date.getHours().toString().padStart(2, '0');
	const minutes = date.getMinutes().toString().padStart(2, '0');
	const seconds = date.getSeconds().toString().padStart(2, '0');
  
	return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  }
function formatTime2(date = new Date()) {
	return dayjs(date).format('YYYY-MM-DD');
}
Page({
	/**
   * 页面的初始数据
   */
	data: {
		inputshow: false,
		inputshow2: false,
		inputlist2: [{ unit: '步', value: '', text: '请输入目标步数' }],
		inputlist: [{ unit: '步', value: '', text: '请输入步数' }, { unit: 'kcal', value: '', text: '请输入能耗' }],
		shebeiicon: 'https://hxhealth.oss-cn-beijing.aliyuncs.com/redstart/sportsAdministration/shouhuan.png',
		fasleshebeiicon: 'https://hxhealth.oss-cn-beijing.aliyuncs.com/redstart/sportsAdministration/gantanhao.png',
		targetSteps: '--',
		percentValue: 0,  //百分比
		kcalValue: '--',
		linedata: null,
		show: false,
		showecharts: false,
		ec: {
			// 初始化图表
			onInit: (canvas, width, height) => {
				//初始化echarts元素，绑定到全局变量，方便更改数据
				chart = echarts.init(canvas, null, {
					width: width,
					height: height
				});
				canvas.setChart(chart);
				return chart;
			}
		},
		currentDevice: null,
		bindDevice: null,
		timer: null,
		bleAvaible: true,
		showDialog: false,
		bindDeviceTextInfo: '',
		step: 0,   //步数
		urlresult:''
		// https://h5.leshiguang.com/t/step/1.0.0/hx/main.html?_accessToken=3D3F26E64DF9136ABE2303EE34B7B529B8B9CC0D8E0B4E29FA0173183DE5D3978D9F7D5F2CB4A192A2C4C0FBF9FB32C3229FC224DB0C14055D358406D75DDD8CA2A6BBBC7DC9B19112106767B8E04F6DB5887642F2AB72E9DAF52A1B7897E0DD1F26DA701CDE5055A9B18E9412A1461E5D0A865F46EF7CC95B058F16D741D75A.F52DFC70E32C5A847107BF81C2AEDDFDC7D00F37D2ABBE7BB5E7F3808DEC3EC8&_userId=9&_subscriptionId=9901&vconsole=0&_requestId=7a5f89f3b176ed32cc61c2215516b4f4#onshow
	},

	/**
   * 生命周期函数--监听页面加载
   */
	onLoad(options) {
		console.log(options);
		// this.drawProgress()
		const { titlename, type } = options
		console.log(titlename);
		wx.setNavigationBarTitle({
		  title: titlename // 设置页面标题
		})
		console.log(type);
		this.setData({
			type
		})
		this.gettoken()
		// this.gethistrorylist(); //查看历史数据
		// this.getloadlist(); //查询当前最新数据
		// this.gettargetSteps()
		
	},
	gettoken() {
		try {
			api.get(`/api/hxhealth/sghealth/token`).then((res) => {
				console.log(res);
				this.getsign()
			});
		} catch (e) {
			console.error(e);
		}
	},
	getsign() {
		try {
			api.get(`/api/hxhealth/sghealth/sign`).then((res) => {
				console.log(res);
				let appKeys = res[0].appKey
				let sign = res[0].sign
				let timestamp = res[0].timestamp
				this.gosanfang(sign,appKeys,timestamp)
				this.setData({
					sign,
					appKeys,
					timestamp
				})
				
			});
		} catch (e) {
			console.error(e);
		}
	},
	gosanfang(sign,appKeys,timestamp) {
		const userInfo = wx.getStorageSync('userInfo')
		var that = this
		wx.request({
			url: `https://api.leshiguang.com/api/sessions/v1.0/associatedBusiness/loginTenant?api_sign=${sign}&api_appKey=${appKeys}&api_version=1.0&api_timestamp=${timestamp}`,
			method: 'POST', // 请求方法为POST
			data: {
				associatedId: userInfo.id, // 请求参数
				notCreate: false,
				softLogin: false
			},
			header: {
			  'content-type': 'application/json' // 设置请求头为JSON格式
			},
			success: function(res) {
			  // 请求成功的回调函数
			  console.log(res.data.data);
			  console.log(res.data.data);
			  var data = res.data.data
			  console.log(that.data.type);
			  var type = that.data.type
			  if(type == 'yundong') {
				that.setData({
					urlresult: `https://h5.leshiguang.com/t/sport/1.3.1/hx/home.html?_accessToken=${data.accessToken}&_userId=${data.userId}&_subscriptionId=9901&_requestId=7a5f89f3b176ed32cc61c2215516b4f4#onshow`
				})
				console.log(that.data.urlresult);
			  }
			  if(type == 'bushu') {
				that.setData({
					urlresult: `https://h5.leshiguang.com/t/step/1.0.0/hx/main.html?_accessToken=${data.accessToken}&_userId=${data.userId}&_subscriptionId=9901&_requestId=7a5f89f3b176ed32cc61c2215516b4f4#onshow`
				})
				console.log(that.data.urlresult);
			  }
			  if(type == 'xinlv') {
				that.setData({
					urlresult: `https://h5.leshiguang.com/t/heartRate/1.0.0/hx/home.html?_accessToken=${data.accessToken}&_userId=${data.userId}&_subscriptionId=9901&_requestId=7a5f89f3b176ed32cc61c2215516b4f4#onshow`
				})
				console.log(that.data.urlresult);
			  }
			  if(type == 'shuimian') {
				that.setData({
					urlresult: `https://h5.leshiguang.com/t/sleep/1.5.4/hx/homepro.html?_accessToken=${data.accessToken}&_userId=${data.userId}&_subscriptionId=9901&_requestId=7a5f89f3b176ed32cc61c2215516b4f4#onshow`
				})
				console.log(that.data.urlresult);
			  }
			  
			},
			fail: function(res) {
			  // 请求失败的回调函数
			  console.log(res.errMsg);
			}
		  });
	},
	// xinlv(){
	// 	console.log('jinlailema--------心率-----',this.data.appKeys);
	// 	const userInfo = wx.getStorageSync('userInfo')
	// 	wx.request({
	// 		url: `https://api.leshiguang.com/api/heartrate/v2.0/upload/uploadHeartRate?api_sign=${this.data.sign}&api_appKey=${this.data.appKeys}&api_version=1.0&api_timestamp=${this.data.timestamp}`,
	// 		method: 'POST', // 请求方法为POST
	// 		data: {
	// 			"associatedId": userInfo.id,
    //             "list": [
    //               {
    //                 "deviceId": "38041300A53D",
    //                 "heartRates": "545a5e5f5d55595459",
    //                 "measurementDate": 1713855000000,
    //                 "quantityOfHeartRate": 9
    //               }
    //             ]

	// 		},
	// 		header: {
	// 		 'associatedId': userInfo.id,
	// 		  'content-type': 'application/json' // 设置请求头为JSON格式
	// 		},
	// 		success: function(res) {
	// 		  // 请求成功的回调函数
	// 		  console.log(userInfo.id);
			 
	// 		},
	// 		fail: function(res) {
	// 		  // 请求失败的回调函数
	// 		  console.log(res.errMsg);
	// 		}
	// 	  });
	// },
	// bushu(){
	// 	console.log('jinlailema-------------',this.data.appKeys);
	// 	const userInfo = wx.getStorageSync('userInfo')
	// 	wx.request({
	// 		url: `https://api.leshiguang.com/api/step/v2.0/upload/uploadBandDeviceStep?api_sign=${this.data.sign}&api_appKey=${this.data.appKeys}&api_version=1.0&api_timestamp=${this.data.timestamp}`,
	// 		method: 'POST', // 请求方法为POST
	// 		data: {
	// 			associatedld: userInfo.id,
	// 			list: [{
	// 				avgHeartRate:'90',
	// 				avgPace: 0,
	// 				avgSpeed: 24346,
	// 				avgStepRate: 3,
	// 				bestSpeed: 0,
	// 				calories: 222,
	// 				dataSource: 0,
	// 				deviceld: "38041300A53D",
	// 				distance: 49,
	// 				endTime: 1713853710000,
	// 				exerciseTime: 1193,
	// 				exerciseType: 6,
	// 				maxHeartRate: 101,
	// 				maxStepRate: 0,
	// 				startTime: 1713852517000,
	// 				step: 68,
	// 				measurementTime: 1713852517000
	// 			}]
	// 		},
	// 		header: {
	// 		 'associatedId': userInfo.id,
	// 		  'content-type': 'application/json' // 设置请求头为JSON格式
	// 		},
	// 		success: function(res) {
	// 		  // 请求成功的回调函数
	// 		  console.log(userInfo.id);
			 
	// 		},
	// 		fail: function(res) {
	// 		  // 请求失败的回调函数
	// 		  console.log(res.errMsg);
	// 		}
	// 	  });
	// },
	jianting() {
		var that = this
		// 监听蓝牙适配器状态变化
		wx.onBluetoothAdapterStateChange((res) => {
			if (res.available) {
			  // 蓝牙已经开启
			  that.initPlugin();
			  setTimeout(() => {
					that.getDeviceList()
				}, 500);
			}
		});
	},
	async getDeviceList() {
		const res = await api.post('/api/user/storage/get', {
			data: {
				'key': 'devicelist'
			}
		})
		if (res[0].value) {
			var array = JSON.parse(res[0].value)
			const listValue = array.filter(item => item.name === 'bracelet')
			if (listValue.length > 0) { // 如果绑定的有设备，直接连接
				if (listValue[0].devicelist.length > 0) {
					this.setData({
						currentDevice: listValue[0].devicelist[0]
					})
					this.onBind()
				}
			}
		}
	},
	getWeekDays() {
		let dates = []
		for (var i = 365; i >= 0; i--) {
			var currentDate = new Date();
			currentDate.setDate(currentDate.getDate() - i);
			var month = ("0" + (currentDate.getMonth() + 1)).slice(-2);
			var day = ("0" + currentDate.getDate()).slice(-2);
			var formattedDate = month + "/" + day;
			dates.push(formattedDate);
		}
		return dates
	},
	gethistrorylist() {
		api
			.post('/api/hxhealth/exams/records', {
				data: {
					everyday: true,
					itemcode: 'lk1591234989246',
					typecode: 'wriststrap',
					everyday: true
				},
				head: {
					firstresult: 0,
					maxresults: 1000,
					bodytype: 'flat',
				}
			})
			.then((res) => {
				// console.log(res);
				console.log('----历史数据----', res);
				if (res.length > 0) {
					const jsonData = res;
					// 提取数据的数组
					const values = [];
					const times = [];

					// 遍历 body 数组
					jsonData.forEach((entry) => {
						// 遍历 devices 数组
						entry.devices.forEach((device) => {
							console.log(device);
							// 找到 code 为 "lk1591234989246" 的项
							const item = device.items.find((item) => item.code === 'lk1591234989246');

							// 如果找到了，将 value 和 time 添加到相应的数组中
							if (item) {
								console.log(item);
								values.push(Number(item.value)); // 将值转换为数字类型
								times.push(entry.time.slice(0, 10).replace(/-/g, '/'));
							}
						});
					});
					const linedata = {
						values,
						times
					};
					console.log(linedata);
					this.setData({
						linedata
					});
					// 模拟获取接口数据
					setTimeout(() => {
						this.getEchartData(linedata);
					}, 1000);
				} else {
					const linedata = {
						values: [],
						times: this.getWeekDays()
					};
					this.setData({
						linedata
					});
					// 模拟获取接口数据
					setTimeout(() => {
						this.getEchartData(linedata);
					}, 1000);
				}
			});
	},
	getloadlist() {
		// 整体列表查询
		api
			.post('/api/exams/lastvalues', {
				data: {
					devkind: 'wriststrap',
					devmode: '',
					itemcode: '',
					typecode: '',
					unionuser: true
				}
			})
			.then((res) => {
				// console.log(res);
				console.log('----最新数据----', res);
				const array = res;
				for (let y = 0; y < array.length; y++) {
					if (array[y].code == 'XYZBQT02') {
						console.log(array[y].value);
						this.setData({
							kcalValue: Number(array[y].value).toFixed(0)
						});
					}
					if (array[y].code == 'lk1591234989246') {
						this.setData({
							step: array[y].value,
						});
					}
				}
			});
	},
	gettargetSteps() {
		console.log('777', this.data.targetSteps);
		let data = {
			"value": this.data.inputlist2[0].value,
			"key": "targetSteps"
		};
		// 目标步数保存
		api
			.post('/api/user/storage/get', {
				data
			})
			.then((res) => {
				this.setData({
					targetSteps: res[0].value?res[0].value:'--'
				});
				console.log(res);
				console.log('----查询目标步数----', res);
			});
	},
	savedevices2() {
		if (this.data.inputlist2[0]) {
			console.log('666', this.data.inputlist2[0]);
			let data = {
				"value": this.data.inputlist2[0].value,
				"key": "targetSteps"
			};
			// 目标步数保存
			api
				.post('/api/user/storage/set', {
					data
				})
				.then((res) => {
					// console.log(res);
					console.log('----保存录入----', res);
					this.getloadlist();
					this.closesaveNickname();
					this.gettargetSteps()
					wx.showToast({
						icon: 'none',
						title: '保存成功'
					});
					this.setData({
						inputshow2: false,
						'inputlist2[0].value': ''
					});
				})
				.catch((e) => {
					console.log(e);
					wx.showToast({
						icon: 'none',
						title: e.faultstring ? e.faultstring : '保存失败'
					});
				});
		}

	},
	savedevices(result,resultkcal) {
		if( result && resultkcal ) {
		let data = {
			name: '运动监测',
			time: formatTime(),
			typecode: 'wriststrap',
			typename: '运动监测',
			devices: [
				{
					name: '运动监测',
					kind: 'wriststrap',
					items: [
						{
							code: 'lk1591234989246',
							checkDate: null,
							level: null,
							value: result,
							deviceBrand: '',
							deviceNo: ''
						},
						{
							code: 'XYZBQT02',
							checkDate: null,
							level: null,
							value: resultkcal,
							deviceBrand: '',
							deviceNo: ''
						}
					]
				}
			]
		};
		this.save(data)
		} else {
			let data = {
				name: '运动监测',
				time: formatTime(),
				typecode: 'wriststrap',
				typename: '运动监测',
				devices: [
					{
						name: '运动监测',
						kind: 'wriststrap',
						items: [
							{
								code: 'lk1591234989246',
								checkDate: null,
								level: null,
								value: result,
								deviceBrand: '',
								deviceNo: ''
							}
						]
					}
				]
			};
			this.save(data)
		}
		
	},
	save(data) {
		// 整体列表保存
		api
			.post('/api/hxhealth/exams/save', {
				data
			})
			.then((res) => {
				// console.log(res);
				console.log('----保存录入----', res);
				this.getloadlist();
				this.closesaveNickname();
				wx.showToast({
					icon: 'none',
					title: '保存成功'
				});
			})
			.catch((e) => {
				console.log(e);
				wx.showToast({
					icon: 'none',
					title: e.faultstring ? e.faultstring : '保存失败'
				});
			});
	},
	openNickname() {
		this.setData({
			inputshow: true
		});
	},
	openNickname2() {
		this.setData({
			inputshow2: true
		});
	},
	closesaveNickname() {
		this.setData({
			inputshow: false
		});
	},
	closesaveNickname2() {
		this.setData({
			inputshow2: false
		});
	},
	userNameInput1(e) {
		this.setData({
			'inputlist[0].value': e.detail.value
		});
	},
	userNameInput2(e) {
		console.log(e.detail.value);
		this.setData({
			'inputlist2[0].value': e.detail.value
		});
	},
	saveNickname() {
		if(!/^[1-9]\d*$/.test(this.data.inputlist[0].value)) {
			wx.showToast({
				title: '请输入正整数',
				icon: 'none',
				duration: 2000
			})
			return
		}
		this.savedevices(this.data.inputlist[0].value);
	},
	saveNickname2() {
		console.log(this.data.inputlist2);
		this.savedevices2();
	},
	modal_click_Hidden() {
		this.setData({
			inputshow: false
		});
	},
	// 绘制图表
	runColumncCanva() {
		var option = {
			title: {
				// text: '次/分',
				textStyle: {
					fontSize: 9,
					color: '#666666'
				}
			},
			color: ['#37A2DA'],
			legend: {
				data: ['运动监测变化趋势'],
				icon: 'circle',
				left: 0,
				itemWidth: 9,
				// itemStyle: {
				//     color: '#5BBF70'
				// },
				textStyle: {
					color: '#333333',
					fontSize: 16
				}
			},
			grid: {
				left: '0%',
				right: '5%',
				bottom: 0,
				top: '15%',
				containLabel: true,
				show: true
			},

			tooltip: {
				show: true,
				trigger: 'axis'
			},
			xAxis: {
				type: 'category',
				boundaryGap: false,
				data: timeArr,
				axisLabel: {
					fontSize: 16,
					rotate: 0 //倾斜度 -90 至 90 默认为0
				}
			},
			yAxis: {
				type: 'value',
				splitLine: {
					lineStyle: {
						type: 'dashed'
					}
				},
				axisLabel: {
					fontSize: 16
				}
			},
			series: seriesDataArr
		};
		//这里一定要做个charts是否存在的判断，因为万一ec那里没有初始化，这里就会报错
		if (chart) {
			chart.setOption(option);
			this.setData({
				show: true
			});
		}
	},
	getEchartData(linedata) {
		seriesDataArr = [
			{
				name: '运动监测变化趋势',
				type: 'line',
				stack: 'Total',
				smooth: true,
				data: linedata.values
			}
		];
		timeArr = linedata.times;
		this.runColumncCanva();
	},
	// 初始化插件
	initPlugin() {
		lsPlugin.init({
			appId: "lx758d9d23a6bac221",
			logger: null,
			// 微信蓝牙开关回调
			onBluetoothAdapterStateChange: (res) => {
				console.log(res, 'BBBBB')
				if (res.available) {
					console.log('手环插件初始化成功')
					this.setData({
						bleAvaible: true
					})
					wx.offBluetoothAdapterStateChange()	
				} else {
					this.setData({
						bleAvaible: false
					})
					console.log(res, '手环插件初始化失败')
				}
			},
		})
	},
	onCancel() {
		this.setData({
			showDialog: false,
		})
		// 停止搜索
		this.stopScan()
	},
	// 扫码设备
	onScan() {
		console.warn('--------------', '扫描')
		lsPlugin.startScanning(device => {
			console.warn('发现设备', device)
			// 判断是否存在A5
			if (device.name.indexOf('HR6') > -1) {
				console.warn('发现HR6设备', device)
				this.setData({
					currentDevice: device
				})
				this.onBind(device)
			} else {
				this.setData({
					bindDeviceTextInfo: '未发现对应的设备'
				})
				setTimeout(() => {
					this.setData({
						showDialog: false,
					})
				}, 500);
			}
			//  // 记录扫描到的设备
			//  const find = this.data.devices.find((item) => item.deviceId === device.deviceId)
			// 	if (typeof find === "undefined") {
			// 		 return this.data.devices.concat(device)
			// 	} else {
			// 		 return this.data.devices
			// 	}
		})
	},
	// 未发现绑定，5秒再扫描一次
	createTimeInter() {
		this.data.timer = setInterval(() => {
			if (!this.data.currentDevice) {
				this.onScan()
			} else {
				this.stopScan()
			}
		}, 5000)
	},
	// 停止扫描
	stopScan() {
		lsPlugin.stopScanning();
	},
	// 解绑设备
	doDeleteMonitorDevice() {
		lsPlugin.deleteMonitorDevice({
			mac: this.data.currentDevice.mac,
		})
	},
	// 添加监听
	doAddMonitorDevice(device) {
		console.log(this.data.currentDevice, 'AAAAAAAAAAAAA')
		let _device = device ? device : this.data.currentDevice
		lsPlugin.addMonitorDevice({
			mac: _device.mac,
			model: _device.model,
		})
	},
	// 添加监听
	onBind(device) {
		return new Promise((resolve, reject) => {
			this.setData({
				bindDeviceTextInfo: '正在绑定设备'
			})
			this.stopScan()
			// 防止嵌套的缓存问题
			let _device = device ? device : this.data.currentDevice
			this.setData({
				currentDevice: _device
			})
			console.log(_device, '--------------开始绑定设备')
			if (_device) {
				console.warn('--------------开始绑定设备')
				// 如果是安卓设备，则需要判断位置是否可用，位置权限是否可用 let { locationEnabled, locationAuthorized } = wx.getSystemInfoSync();
				lsPlugin.bindDevice({
					mac: _device.mac,
					callback: res => {
						console.warn('绑定设备结束', res)
						// 绑定成功
						if (res.bindState === 4) {
							const bindDevice = {
								mac: res.mac,
								bindState: res.bindState,
								model: _device.model,
								localName: _device.localName,
							}
							this.setData({
								bindDevice: bindDevice
							})
							// 监听数据
							console.warn('开始监听数据')
							this.onDataReport()
							this.doAddMonitorDevice()
							this.setData({
								bindDeviceTextInfo: '设备绑定成功'
							})
							resolve()
							setTimeout(() => {
								this.setData({
									showDialog: false,
								})
							}, 500);
							// 绑定失败
						} else if (res.bindState) {
							console.log('绑定失败')
							this.setData({
								bindDeviceTextInfo: '设备绑定失败'
							})
							reject()
							setTimeout(() => {
								this.setData({
									showDialog: false,
								})
							}, 500);
						} else if (res?.errorCode) {
							console.log('绑定失败')
							this.setData({
								bindDeviceTextInfo: '设备绑定失败'
							})
							reject()

							setTimeout(() => {
								this.setData({
									showDialog: false,
								})
							}, 500);
						} else {
							this.setData({
								bindDeviceTextInfo: '设备绑定失败'
							})
							reject()
							setTimeout(() => {
								this.setData({
									showDialog: false,
								})
							}, 500);
						}
					}
				});
			} else {
				// showToast({title: "绑定失败，设备断开", icon: 'none'});
			}
		})
	},
	// 监听数据上报
	onDataReport() {
		console.log('监听数据开始')
		lsPlugin.$on({
			eventName: "dataReport",
			eventKey: 'wo',  // 唯一标识，同一标识的监听会被覆盖
			callback: (device, data) => {
				const arr = ["a5Daily", "a5HR", "a5Sleep", 'a5SportCalories', 'a5SportReport', 'bloodOxygen', 'a5SportStatus']
				// https://mp.weixin.qq.com/wxopen/plugindevdoc?appid=wxe3d2a6ab8dd5b49b&token=1156697109&lang=zh_CN
				if (!!data?.dataType && arr.indexOf(data?.dataType) > -1) {
					console.log(data, '收到数据了')
					if (data.dataType === 'a5Daily') {
						if (data.list && data.list.length > 0) {
							this.setData({
								step: data.list[0].step, //步数
								kcalValue: data.list[0].calories.toFixed(0), //卡路里
								distance: data.list[0].distance, //距离米
								examount: data.list[0].examount, //运动量
								exerciseTime: data.list[0].exerciseTime, //运动时间
								silenceHeartRate: data.list[0].silenceHeartRate, //静息心率
								utc: formatDatelx(data.list[0].utc) //测量时间
							})
							console.log(this.data.step);
							const perc = Math.round(data.list[0].step / Number(this.data.targetSteps)).toFixed(2)
							if(this.data.step!==0) {
								this.savedevices(this.data.step,this.data.kcalValue)
							}
							console.log(perc, 'percpercperc')
							this.setData({
								percentValue: perc * 100,
								showecharts: true
							})
						}
					}
					// 记录最后一次收到的测试数据
					// setCurrentTestData(data)
				}
				// 记录所有收到的测试数据
				// setTestData(testData => testData.concat(data))
			},
		});
	},
	// 链接设备
	goBindEq() {
		// if(!this.data.bleAvaible) {
		// 	wx.showToast({
		// 		title: '蓝牙初始化失败',
		// 		icon: 'none',
		// 		duration: 2000
		// 	})
		// 	return
		// }
		// this.setData({
		// 	bindDeviceTextInfo: '正在搜索手环设备'
		// })
		// this.setData({
		// 	showDialog: true
		// })
		// this.onScan()
		// this.createTimeInter()
		wx.navigateTo({
			url: '/sportsAdministration/pages/device/index'
		});
	},

	/**
   * 生命周期函数--监听页面初次渲染完成
   */
	onReady: function () {
		// var that = this;
		// that.canvasRing = that.selectComponent('#canvasRing');
		// that.canvasRing.showCanvasRing();
	},

	/**
   * 生命周期函数--监听页面显示
   */
	onShow() {
		// wx.openBluetoothAdapter({
		// 	success: (res) => {
		// 		console.log('蓝牙功能已开启！')
		// 		this.initPlugin()
		// 		setTimeout(() => {
		// 			this.getDeviceList()
		// 		}, 500);
		// 	},
		// 	fail: () =>  {
		// 		this.setData({
		// 			bindDeviceTextInfo: '蓝牙未开启，请开启蓝牙'
		// 		})
		// 		this.setData({
		// 			showDialog: true
		// 		})
		// 		this.jianting()
		// 		}
		// 	})
	 },

	/**
   * 生命周期函数--监听页面隐藏
   */
	onHide() { },

	/**
   * 生命周期函数--监听页面卸载
   */
	onUnload() {
		clearInterval(this.data.timer)
		this.doDeleteMonitorDevice()
		wx.offBluetoothAdapterStateChange()	
	},

	/**
   * 页面相关事件处理函数--监听用户下拉动作
   */
	onPullDownRefresh() { },

	/**
   * 页面上拉触底事件的处理函数
   */
	onReachBottom() { },

	/**
   * 用户点击右上角分享
   */
	onShareAppMessage() { }
});
